const express = require('express');
const fs = require('fs').promises;
const app = express();
const { fileURLToPath } = require('url');
const path = require('path');
const { dirname } = path;
const currentFilename = fileURLToPath(require('url').pathToFileURL(__filename));
const __dirname2 = dirname(currentFilename);
let player = path.join(__dirname2, '../player/player.json') 
app.use(express.json());

app.post('/', async (req, res) => {
  let { nickname, userid, bot, plugin } = req.body;
  if(bot.includes(`alemon`))bot = `alemonjs`
  if (!userid || userid === '') {
    return res.status(400).json({ error: '请求错误' });
  }

  const list = JSON.parse(await fs.readFile(player, 'utf-8'));
  const user = list.find(item => item.nickname === nickname);

  if (user) {
    let pluginlist = user.plugin

    if (user.bot !== bot) {
      user.bot = bot;
      console.log(`更新用户${nickname}的机器人,目前为${bot}`);
    }

    if (pluginlist.includes(plugin)) {
      res.status(400).json({ code: 400, msg: '插件已存在' });
      console.log(`用户${nickname}插件已存在`);
    } else {
      pluginlist.push(plugin);
      res.status(200).json({ code: 200, msg: `新插件：${plugin}已记录` });
      console.log(`用户${nickname}添加插件${plugin}`);
    }
  } else {
    list.push({ nickname, userid, bot, plugin: [plugin] });
    res.status(200).json({ code: 200, msg: '欢迎使用wuzhe-plugin插件' });
    console.log(`新增存档${nickname}`);
  }

  const newJson = JSON.stringify(list, null, '\t');
  await fs.writeFile(player, newJson, 'utf8').catch(error => console.error('保存数据时发生错误:', error));
});

module.exports = app;